// pages/home/home.js
const app = getApp();
const service = require("../../service/port.js");
const activityservice = require("../../service/activity.js");
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    propsData: {
      id: 1,
    }, //给签到组件传递的参数
    pageNum: 1, // 当前请求的page
    pageSize: 4, // 请求数据的size
    noData: false, // 是否有更多数据
    swiperList: [],
    productList: [],
    showjoin: false,
    show: false,
    todaySignN: true,
    todaySignY: false,
    needSign: true,
    seckillAd: '', //秒杀广告位
    groupAd: '', //拼团广告
    lotteryAd:'',//幸运大抽奖广告位
    fixedAd: '', //打包一口价广告
    seckilData: [], //秒杀
    topdata: [], //热销
    coupondata: [], //优惠卷
    startTime: "",
    endTime: "",
    showOverlay: false,
    overlayinfo: {},
    showObj: {
      search: true,
      group: true,
      lottery: true,
      pakage: true,
      seckill: true,
      hot: true,
      moreHot: true,
      coupon: true
    }

  },
  getList(callback) {
    service.getHostProduct({
        pageSize: this.data.pageSize,
        pageNum: this.data.pageNum,
      },
      (res) => {
        //console.log(res);
        callback(res);
      }
    );
  },
  adGoToProductDetail(e) {
    let item = e.currentTarget.dataset.item
    if (item.isDefault == 1) {
      wx.navigateTo({
        url: "/pages/product/productDetail/index?id=" + item.spuId,
      });
    }
  },
  goToProductDetail(e) {
    console.log(1111, e)
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "/pages/product/productDetail/index?id=" + id,
    });
  },
  gogoods(item) {
    console.log(item.target.dataset.item);
    if (item.currentTarget.dataset.item.isDefault == "1") {
      wx.navigateTo({
        url: "/pages/product/productDetail/index?id=" +
          item.target.dataset.item.spuId,
      });
    }
  },
  gosearchList() {
    wx.navigateTo({
      url: "/pages/searchList/index",
    });
  },
  getnewcoupon() {
    service.getNewCoupon(res => {
      this.setData({
        coupondata: res.data
      })
    })
  },
  onClickShow() {
    let customerId = wx.getStorageSync("userInfo").id;
    if (app.globalData.userInfo == null) {
      wx.navigateTo({
        url: "/pages/remindlogin/index",
      });
    } else {
      // console.log("1231234");
      service.signIn(customerId, (res) => {
        if (res.code == "00000") {
          this.setData({
            show: true,
            propsData: res.data,
            todaySignN: false,
            todaySignY: true,
          });
        } else if (res.code == "B0001") {
          this.setData({
            show: false,
            todaySignN: false,
            todaySignY: true,
          });
          setTimeout(function () {
            wx.showToast({
              title: "今天已签到",
              icon: "none",
              duration: 2000,
            });
          }, 100)
        }
      });
    }
  },


  joinNow() {
    if (app.globalData.userInfo == null) {

      wx.navigateTo({
        url: "/pages/remindlogin/index",
      });
    } else {
      service.getAgentok(wx.getStorageSync("userInfo").id, res => {
        //console.log(res);
        if (res.data == false) {
          Toast.fail('您已经是代理，请到管理端启用！')
        } else {
          wx.navigateTo({
            url: "/pages/mine/agency/index",
          });
        }
      })
    }
  },
  onClickHide() {
    this.setData({
      show: false,
    });
  },
  getBannerList: function () {
    service.getbannerList({
      "banner": {
        "name": "",
        "type": "1", //广告类型（位置） 1：首页banneer广告位 2：首页推广位 3：订单支付完成后页面广告位 4：我的页面底部广告位 5：开屏弹窗广告位 6: 秒杀广告 7：拼团广告 8：打包一口价广告 9：优惠券广告
        "createTime": "",
        "createTime2": ""
      },
      "queryRequest": {
        "pageSize": "100",
        "pageNum": "1"
      }
    }, (res) => {
      //console.log(res);
      this.setData({
        swiperList: res.data.rows,
      });
    });
  },
  getAdlist() {
    const self = this;
    service.getbannerList({
      "banner": {
        "name": "",
        "type": "", //广告类型（位置） 1：首页banneer广告位 2：首页推广位 3：订单支付完成后页面广告位 4：我的页面底部广告位 5：开屏弹窗广告位 6: 秒杀广告 7：拼团广告 8：打包一口价广告 9：优惠券广告
        "createTime": "",
        "createTime2": ""
      },
      "queryRequest": {
        "pageSize": "100",
        "pageNum": "1"
      }
    }, (res) => {
      //console.log(res.data.rows);
      for (let i = 0; i < res.data.rows.length; i++) {
        const element = res.data.rows[i];
        // 1：首页banneer广告位 2：首页推广位 3：订单支付完成后页面广告位 4：我的页面底部广告位 5：开屏弹窗广告位 6: 秒杀广告
        // 7：拼团广告 8：打包一口价广告 9：优惠券广告 10 : 大转盘广告  幸运大抽奖广告位  11 :  商品推广背景图
        if (element.type == 6) {
          self.setData({
            seckillAd: element // 秒杀广告
          })
        } else if (element.type == 7) {
          self.setData({
            groupAd: element // 拼团广告
          })
        } else if (element.type == 8) {
          self.setData({
            fixedAd: element // 打包一口价广告
          })
        }else if (element.type == 10) {
          self.setData({
            lotteryAd: element // 幸运大抽奖广告位
          })
        }
      }
    });
  },
  formatDateTime(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    var second = date.getSeconds();
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  },
  /*获取秒杀数据 */
  getseckilData() {
    var self = this;
    let endTime = self.formatDateTime(new Date()).split(" ")[0] + ' 23:59:59'
    activityservice.getSeckillSkuList({
      //列表参数
      "data": {
        "startTimes": self.formatDateTime(new Date()),
        "endTimes": endTime,
        "isPaging": 1,
        "customerId": ""
      },
      "queryRequest": {
        "pageSize": "4",
        "pageNum": "1"
      }
    }, res => {
      console.log(res.data.rows)
      self.setData({
        seckilData: res.data.rows
      })
    })
  },
  /*获取热销数据 */
  gettopdata() {
    let self = this;
    service.getSelectIsHot(res => {
      //console.log(res)
      self.setData({
        topdata: res.data
      })
    })
  },
  /*优惠劵点击事件 */
  couponTo() {

    let userId = wx.getStorageSync('userInfo').id

    if (!userId) {
      wx.showToast({
        title: '当前用户未登录!',
        icon: 'none',
        duration: 2000
      })
      return
    }

    wx.navigateTo({
      url: '/pages/golddiscounts/index',
    })
  },
  /**热销商品 跳转 */
  topgoodTo(e) {
    wx.navigateTo({
      url: '/pages/product/productDetail/index?id=' + e.currentTarget.dataset.index.id,
    })
  },
  onLoad: function (options) {
    wx.setStorageSync('qrcodeId', 0)
    if (app.globalData.time == 1) {
      service.getbannerList({
        "banner": {
          "type": 5, //广告类型（位置） 1：首页banneer广告位 2：首页推广位 3：订单支付完成后页面广告位 4：我的页面底部广告位 5：开屏弹窗广告位 6: 秒杀广告 7：拼团广告 8：打包一口价广告 9：优惠券广告 
        },
        "queryRequest": {
          "pageSize": this.data.pageSize,
          "pageNum": this.data.pageNum
        }
      }, res => {
        console.log(res)
        this.setData({
          overlayinfo: res.data.rows[0]
        })
        this.timer()
      })

    };
    if (options.id) {
      app.getAppCode(options.id)
      wx.setStorageSync('qrcodeId', options.id || 0)
    };
    this.getBannerList();
    this.getAdlist();
    service.getshowModel("首页", res => {
     // console.log(res)
      var obj = this.data.showObj;
      for (let i = 0; i < res.data.length; i++) {
        const element = res.data[i];
        if (element.ufName == "搜索") {
          obj.search = element.ufIsOpen == 1 ? true : false
        } else if (element.ufName == "抽奖") {
          obj.lottery = element.ufIsOpen == 1 ? true : false
        } else if (element.ufName == "打包一口价") {
          obj.pakage = element.ufIsOpen == 1 ? true : false
        } else if (element.ufName == "限时秒杀") {
          if (element.ufIsOpen == 1) {
            obj.seckill = true;
            this.getseckilData();
          } else {
            obj.seckill = false
          }

        } else if (element.ufName == "热销") {
          if (element.ufIsOpen == 1) {
            obj.hot = true
            this.gettopdata();
          } else {
            obj.hot = false
          }

        } else if (element.ufName == "更多热卖") {
          if (element.ufIsOpen == 1) {
            obj.moreHot = true;
            wx.showLoading({
              title: "加载中...",
            });
            const self = this;
            this.getList(function (res) {
              res.data.rows.forEach((item) => {
                if (item.images) {
                  var imagedata = JSON.parse(item.images);
                  if (imagedata != 1) {
                    var url = imagedata.temBanner.split(",");
                    item.url = url[0];
                  }
                }
              });
              self.setData({
                productList: res.data.rows,
              });
              wx.hideLoading();
            });
          } else {
            obj.moreHot = false
          }

        } else if (element.ufName == "优惠卷") {
          if (element.ufIsOpen == 1) {
            obj.coupon = true
            this.getnewcoupon();
          } else {
            obj.coupon = false
          }

        } else if (element.ufName == "拼团") {
          obj.group = element.ufIsOpen == 1 ? true : false
        }
      }
      this.setData({
        showObj: obj
      })
    });

    // 发送接口请求   

    this.getsignInfo();

  },
  getsignInfo() {
    // service.getSignStatus(res => {
    //   console.log(res)
    //   if (res.data == 1) {
    //     this.setData({
    //       needSign: true
    //     })
    //     if (wx.getStorageSync("userInfo").id) {
    //       service.isSign(wx.getStorageSync("userInfo").id, res => {
    //         //console.log(res)
    //         if (res.data == true) {
    //           this.setData({
    //             todaySignN: false,
    //             todaySignY: true,
    //           })
    //         }
    //       })
    //     }
    //   } else {
    //     this.setData({
    //       needSign: false
    //     })
    //   }
    // });


  },
  joinDelegete() {
    wx.showToast({
      title: '暂未开放！',
      icon: 'none',
      duration: 2000
    })
  },
  groupTo() {
    wx.navigateTo({
      url: '/pages/activity/group/index',
    })
  },
  fixedTo() {
    if (app.globalData.userInfo == null) {

      wx.navigateTo({
        url: "/pages/remindlogin/index",
      });
    } else {
      wx.navigateTo({
        url: '/pages/activity/fixedprice/index',
      })
    }
  },
  seckillTo() {
    wx.navigateTo({
      url: '/pages/activity/seckill/index',
    })
  },
  gooddetailTo(e) {
    console.log(e.currentTarget.dataset.index)
    var currentTime = new Date().getTime()
    var startTime = new Date(e.currentTarget.dataset.index.startTime).getTime()
    var time = "";
    var status = false
    if (currentTime < startTime) {
      time = e.currentTarget.dataset.index.startTime
      status = false
    } else {
      time = e.currentTarget.dataset.index.endTime
      status = true
    }
    wx.navigateTo({
      url: '/pages/activity/goodDetail/index?id=' + e.currentTarget.dataset.index.id + "&endTime=" + time + "&status=" + status,
    })
  },
  onShow: function () {
    this.getBannerList();
    this.getAdlist();
    service.getshowModel("首页", res => {
      //console.log(res)
      var obj = this.data.showObj;
      for (let i = 0; i < res.data.length; i++) {
        const element = res.data[i];
        if (element.ufName == "搜索") {
          obj.search = element.ufIsOpen == 1 ? true : false
        } else if (element.ufName == "抽奖") {
          obj.lottery = element.ufIsOpen == 1 ? true : false
        } else if (element.ufName == "打包一口价") {
          obj.pakage = element.ufIsOpen == 1 ? true : false
        } else if (element.ufName == "限时秒杀") {
          if (element.ufIsOpen == 1) {
            obj.seckill = true;
            this.getseckilData();
          } else {
            obj.seckill = false
          }

        } else if (element.ufName == "热销") {
          if (element.ufIsOpen == 1) {
            obj.hot = true
            this.gettopdata();
          } else {
            obj.hot = false
          }

        } else if (element.ufName == "更多热卖") {
          if (element.ufIsOpen == 1) {
            obj.moreHot = true;
            wx.showLoading({
              title: "加载中...",
            });
            const self = this;
            this.getList(function (res) {
              res.data.rows.forEach((item) => {
                if (item.images) {
                  var imagedata = JSON.parse(item.images);
                  if (imagedata != 1) {
                    var url = imagedata.temBanner.split(",");
                    item.url = url[0];
                  }
                }
              });
              self.setData({
                productList: res.data.rows,
              });
              wx.hideLoading();
            });
          } else {
            obj.moreHot = false
          }

        } else if (element.ufName == "优惠卷") {
          if (element.ufIsOpen == 1) {
            obj.coupon = true
            this.getnewcoupon();
          } else {
            obj.coupon = false
          }

        } else if (element.ufName == "拼团") {
          obj.group = element.ufIsOpen == 1 ? true : false
        }
      }
      this.setData({
        showObj: obj
      })
    });

    // // 发送接口请求
    // const self = this;
    // wx.showLoading({
    //   title: "加载中...",
    // });
    // if(this.data.pageNum!=1){
    //   this.setData({
    //     pageNum:this.data.pageNum-1,
    //     noData: false
    //   })
    // }
    // this.getList(function (res) {
    //   res.data.rows.forEach((item) => {
    //     if (item.images) {
    //       var imagedata = JSON.parse(item.images);
    //       if (imagedata != 1) {
    //         var url = imagedata.temBanner.split(",");
    //         item.url = url[0];
    //       }
    //     }
    //   });
    //   self.setData({
    //     productList: res.data.rows,
    //   });
    //   wx.hideLoading();
    // });
    // this.getsignInfo();
    // this.getBannerList();

    // service.getcustomerDetail(wx.getStorageSync("userInfo").id, res => {
    //   //console.log(res);

    //   service.getAgentok(wx.getStorageSync("userInfo").id, res1 => {
    //     // if (res.data[0].isAgent == '1') {
    //     //   this.setData({
    //     //     showjoin: false,
    //     //   });
    //     // } else {
    //     //   this.setData({
    //     //     showjoin: true,
    //     //   });
    //     // }   
    //     //console.log(res1)
    //     if (res1.data.status == '0') {
    //       this.setData({
    //         showjoin: false,

    //       });
    //     } else{
    //       if(res.data[0].isAgent == '1'){
    //         this.setData({
    //           showjoin: false,
    //         });
    //       }else{
    //         this.setData({
    //           showjoin: true,
    //         });
    //       }

    //     }

    //     // if (res.data == false) {
    //     //   Toast.fail('您已经是代理，请到管理端启用！')
    //     // } else {
    //     //   wx.navigateTo({
    //     //     url: "/pages/mine/agency/index",
    //     //   });
    //     // }
    //   })
    // })
    // if (
    //   wx.getStorageSync("userInfo") &&
    //   wx.getStorageSync("userInfo").isAgent == "1"
    // ) {
    //   this.setData({
    //     showjoin: false,
    //   });
    // } else {
    //   this.setData({
    //     showjoin: true,
    //   });
    // }
  },
  timer: function () {

    setTimeout(() => {
      this.setData({
        showOverlay: true
      });
    }, 1000);
  },
  onClickHide() {
    this.setData({
      showOverlay: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //请求数据
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getBannerList()
    this.setData({
      pageNum: 1,
      noData: false,
    });
    const self = this;

    this.getList(function (res) {
      res.data.rows.forEach((item) => {
        var imagedata = JSON.parse(item.images);
        if (imagedata != 1) {
          var url = imagedata.temBanner.split(",");
          item.url = url[0];
        }
      });
      self.setData({
        productList: res.data.rows,
      });
      //this.getsignInfo();
      // 隐藏加载状态
      // wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.noData) return;
    wx.stopPullDownRefresh();
    // wx.showNavigationBarLoading() //在标题栏中显示加载

    const prolist = this.data.productList;
    let page = this.data.pageNum;
    this.setData({
      // 每次下拉 page+1
      pageNum: ++page,
    });
    const self = this;

    this.getList(function (res) {
      if (res.data.rows.length == 0) {
        self.setData({
          noData: true,
        });
      } else {
        res.data.rows.forEach((item) => {
          var imagedata = JSON.parse(item.images);
          if (imagedata != 1) {
            var url = imagedata.temBanner.split(",");
            item.url = url[0];
          }
          prolist.push(item);
        });
        self.setData({
          productList: prolist,
        });
      }
      // 隐藏加载状态
      // wx.hideNavigationBarLoading()
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  onUnload: function () {
    app.globalData.time = 2;
  },
  groupGame() {
    wx.navigateTo({
      url: '/pages/mine/game/index',
    })
  }
});